package com.david.zhufengfm.utils;

import android.os.Build;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * Created by sdw on 2015/10/12.
 */
public final class HttpTools {

    public static final String USER_AGENT = "ting_4.1.7(" + Build.MODEL + Build.VERSION.SDK_INT + ")";

    private HttpTools (){}
    private static final int CONNECT_TIMEOUT=5000;
    public static final int READ_TIMEOUT=30000;

    public static byte[] doGet(String url){
        byte[]ret=null;

        if (url != null) {
            HttpURLConnection conn=null;
            try {
                URL u=new URL(url);
                conn= (HttpURLConnection) u.openConnection();
                //设置连接的配置
                conn.setConnectTimeout(CONNECT_TIMEOUT);
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setRequestMethod("GET");
                //完善Http请求的内容
                //1.设定通用的Http头信息
                //设置Accept头信息，告诉服务器，客户端能够接受什么样的数据
//                conn.setRequestProperty("Accept","application/*,text/*,image/*,*/*");
                //设置接受的内容压缩编码算法
                conn.setRequestProperty("Accept-Encoding","gzip");
                //设置User-Agent
                //Build.VERSION.SDK_INT 手机的API级别
                conn.setRequestProperty("User-Agent", USER_AGENT);
                conn.connect();
                int code=conn.getResponseCode();
                if (code == 200) {
                    //TODO 给data赋值
                    ByteArrayOutputStream bos=null;
                    InputStream is=null;
                    try {
                        is=conn.getInputStream();
                        // TODO 检查网络数据是否经过 GZIP 的压缩;如果压缩,需要解开

                        // 1. 检测  Content-Encoding
//                        String encoding = conn.getHeaderField("Content-Encoding");
                        String encoding = conn.getContentEncoding();

                        // 2. 判断是否经过 gzip

                        if("gzip".equals(encoding)){
                            is = new GZIPInputStream(is);
                        }
                       ret= StreamUtil.readStream(is);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                       StreamUtil.close(is);
                        StreamUtil.close(bos);
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



        return  ret;
    }
}
